<?php

namespace app\store\service;
use app\common\model\HomePage;
use app\common\model\MerchantContact;
use app\common\model\Order;
use app\common\model\Product;
use app\common\model\Store;
use app\Response;
use think\facade\Config;
use think\facade\Cache;

class IndexService
{
    public static function wxIndex($type,$page,$num){
        $info = [];
        $banner  = HomePage::dataList($type,$page,$num);
        if(!empty($banner)){
            $info["banner"] = $banner->toArray();
        }else{
            $info["banner"] = [];
        }
        $p_where[] = ["enable","=",1];
        $p_field = "id,p_num,p_name,img_json,supply_price,commission_rate,commission_price";
        $product = Product::dataList($p_where,1,3,$p_field,"addtime desc");
        if(!empty($product)){
            $info["tj_product"] = $product->toArray();
        }else{
            $info["tj_product"] = [];
        }

        return Response::wrapData($info);
    }

    /**** 门店列表
    */
    public static function storeListService($page,$num,$province,$city,$area,$keywords,$longitude,$latitude){
        $where[] = ["enable","=",1];
        if(!empty($province)){
            $where[] = ["province","like","%.$province.%"];
        }
        if(!empty($city)){
            $where[] = ["city","like","%.$city.%"];
        }
        if(!empty($area)){
            $where[] = ["district","like","%.$area.%"];
        }
        if(!empty($keywords)){
            $where[] = ["store_name|address","like","%.$keywords.%"];
        }
        $list = Store::dataList($where,$page,$num);
        if(!empty($list)){
            $list = $list->toArray();
            foreach ($list as $k=>$v){
                $list[$k]["addtime"] = !empty($v["addtime"])?date("Y-m-d H:i:s",$v["addtime"]):"";
            }
            $count = Store::dataCount($where);
        }else{
            $count = 0;
        }
        return Response::wrapData($list,$count);
    }


    /***
    */
    public static function contactAddService($data){
        $data = [
            "name" => $data["name"],
            "phone" => $data["phone"],
            "wx" => $data["wx"],
            "operate" => $data["operate"],
            "delivery_add" => $data["delivery_add"],
            "addtime" => time()
        ];
        $res = MerchantContact::addInfo($data);
        if($res){
            return Response::wrapData();
        }else{
            return Response::wrapError(0,"操作失败!");
        }
    }
    /** 创建微信小程序分享二维码
    */
    public static function makeWxCode($url,$type){
        header("Content-type:image/png");
        //配置APPID、APPSECRET
        if($type == 1){
            $APPID = Config::get("app.wx_xcx_AppID");
            $APPSECRET = Config::get("app.wx_xcx_AppSecret");
        }else{
            $APPID = Config::get("app.mechant_wx_xcx_AppID");
            $APPSECRET = Config::get("app.mechant_wx_xcx_AppSecret");
        }
        if (app('cache')->has("access_token".$type)) {
            $access_token = app('cache')->get("access_token".$type);
        }else{
            Cache::delete("access_token".$type);
            //获取access_token
            $access_token_url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$APPID&secret=$APPSECRET";
            $json = self::httpRequest( $access_token_url );
            $json = json_decode($json,true);
            if(!isset($json['access_token']))
            {
                return Response::wrapError(0,"微信小程序码鉴权失败!");
            }
            $access_token = $json['access_token'];
            Cache::set("access_token".$type,$json['access_token'],300);
        }
        $qcode ="https://api.weixin.qq.com/wxa/getwxacode?access_token=$access_token";
        $param = json_encode(array("path"=>$url));
        $result = self::httpRequest($qcode, $param,"POST");
        //生成二维码

        $type = getimagesizefromstring($result)['mime']; //获取二进制流图片格式
//        header('Content-Type:image/'.$type);
//        $base64String = 'data:' . $type . ';base64,' . chunk_split(base64_encode($result));
//        $base64String = chunk_split(base64_encode($result));
        $base64String = base64_encode($result);
        ob_end_clean();
        return Response::wrapData($base64String);
    }

    /**
    */
    public static function makeOrderPickUpCode($user_id,$id){
        $info = Order::dataInfo(["id"=>$id,"uid"=>$user_id]);
        if(empty($info)){
            return Response::wrapError(0,"订单信息异常");
        }else{
            $key = $info["id"].$info["o_pro_num"].$user_id.$info["addtime"];
            $data = [
                "order_id" => $info["id"],
                "order_pro" => $info["o_pro_num"],
                "key" => md5($key),
            ];
            $codeData = self::makeCode(json_encode($data));
            echo "<img src="."data:image/jpg;base64,".$codeData.">";exit;
            return Response::wrapData($codeData);
        }
    }

    public static function httpRequest($url, $data='', $method='GET'){
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0);
        curl_setopt($curl, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']);
        curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1);
        curl_setopt($curl, CURLOPT_AUTOREFERER, 1);
        if($method=='POST')
        {
            curl_setopt($curl, CURLOPT_POST, 1);
            if ($data != '')
            {
                curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
            }
        }

        curl_setopt($curl, CURLOPT_TIMEOUT, 30);
        curl_setopt($curl, CURLOPT_HEADER, 0);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        $result = curl_exec($curl);
        curl_close($curl);
        return $result;
    }


    public static function makeCode($data){
        header("Content-type:image/png");
        require "../vendor/phpqrcode/phpqrcode.php";
        $qRcode = new \QRcode();

        // 纠错级别：L、M、Q、H
        $level = 'L';
        // 点的大小：1到10,用于手机端4就可以了
        $size = 4;
        // 生成的文件名
        $qRcode->png($data, false, $level, $size);
        $imagestring = base64_encode(ob_get_contents());
        ob_end_clean();
        return $imagestring;
    }

}